package com.rpframework.module.common.bottom.controller;

import com.rpframework.module.common.bottom.entity.enums.RequestType;
import com.rpframework.module.common.bottom.enums.FileType;
import com.rpframework.module.common.springmvc.annotation.AutoMapping;
import com.rpframework.module.common.url.RequestDescription;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@RequestMapping
@Controller("commonFileSeeController")
@RequestDescription("文件查看")
@AutoMapping(RequestType.NONE)
public class FileSeeController {

    @RequestMapping("/download/{type}/{filePath}/{fileName:.*}")
    public void download(@PathVariable("type") FileType type, @PathVariable("filePath") String filePath, @PathVariable("fileName") String fileName, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        try {
            InputStream inputStream = new FileInputStream(FileType.getUploadFile(type, filePath, fileName));

            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }

            // 这里主要关闭。
            os.close();

            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getPath(FileType type, String filePath, String fileName) {
        return "/file/see/download/" + type.name() + "/" + filePath + "/" + fileName;
    }
}
